﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHibernate.Burrow;
using NHibernate.Burrow.Configuration;
using NHibernate.Burrow.Util;
using Ornament.Util.NHibernateHelper;
using Ornament.Util.NHibernateHelper.DataAccess;

public partial class Admin_System_Controls_Setting : UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindFileList();
            FileChanging(DropDownListConfigFiles, EventArgs.Empty);
        }
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        if (ButtonSave == sender)
        {
            var access = new NHibernateSettingDataAccess();
            NHibernateSetting nh = access.Get(DropDownListConfigFiles.SelectedValue);
            SessionFactory sessionFactory = nh[DropDownListSessionFactory.SelectedValue];

            BaseInfo1.UpdateValueOn(sessionFactory);
            runtimeSetting.UpdateValueOn(sessionFactory);
            access.Save(nh);
        }
        else
        {
            var sc = new SchemaUtil();
            sc.CreateSchemas();

            //var sc = new SchemaUtil();
            //sc.DropSchemas(true, false);
            //sc.CreateSchemas();
        }
    }

    protected void FileChanging(object sender, EventArgs e)
    {
        var dropdownlist = (DropDownList) sender;
        if (dropdownlist.SelectedIndex != -1)
        {
            var access = new NHibernateSettingDataAccess();
            NHibernateSetting nh = access.Get(dropdownlist.SelectedValue);
            BindSessionFactory(nh.GetSessionFactoryNames());
            if (DropDownListSessionFactory.Items.Count != 0)
            {
                BindToCurrentSessionFactory();
            }
        }
    }

    #region bind to ui

    private void BindFileList()
    {
        var s = ConfigurationManager.GetSection("NHibernate.Burrow") as NHibernateBurrowCfgSection;
        //绑定配置列表
        foreach (IPersistenceUnitCfg a in s.PersistenceUnits)
        {
            var lt = new ListItem {Text = a.NHConfigFile, Value = MapPath(a.NHConfigFile)};
            DropDownListConfigFiles.Items.Add(lt);
        }
    }

    private void BindSessionFactory(string[] sessionFactoryName)
    {
        foreach (string s in sessionFactoryName)
        {
            DropDownListSessionFactory.Items.Add(new ListItem {Text = s, Value = s});
        }
        DropDownListSessionFactory.SelectedIndex = 0;
    }

    private void BindToCurrentSessionFactory()
    {
        var access = new NHibernateSettingDataAccess();
        NHibernateSetting nh = access.Get(DropDownListConfigFiles.SelectedValue);
        SessionFactory sessionFactory = nh[DropDownListSessionFactory.SelectedValue];
        BaseInfo1.DataBind(sessionFactory);
        runtimeSetting.DataBind(sessionFactory);
    }

    #endregion bind to ui
}